/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Controller;

import Controller.exceptions.IllegalOrphanException;
import Controller.exceptions.NonexistentEntityException;
import Controller.exceptions.PreexistingEntityException;
import Controller.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Model.Creditos;
import Model.Usuarios;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author PaolaRestrepo
 */
public class UsuariosJpaController implements Serializable {

    public UsuariosJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Usuarios usuarios) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (usuarios.getCreditosCollection() == null) {
            usuarios.setCreditosCollection(new ArrayList<Creditos>());
        }
        if (usuarios.getCreditosCollection1() == null) {
            usuarios.setCreditosCollection1(new ArrayList<Creditos>());
        }
        if (usuarios.getCreditosCollection2() == null) {
            usuarios.setCreditosCollection2(new ArrayList<Creditos>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Collection<Creditos> attachedCreditosCollection = new ArrayList<Creditos>();
            for (Creditos creditosCollectionCreditosToAttach : usuarios.getCreditosCollection()) {
                creditosCollectionCreditosToAttach = em.getReference(creditosCollectionCreditosToAttach.getClass(), creditosCollectionCreditosToAttach.getIdCredito());
                attachedCreditosCollection.add(creditosCollectionCreditosToAttach);
            }
            usuarios.setCreditosCollection(attachedCreditosCollection);
            Collection<Creditos> attachedCreditosCollection1 = new ArrayList<Creditos>();
            for (Creditos creditosCollection1CreditosToAttach : usuarios.getCreditosCollection1()) {
                creditosCollection1CreditosToAttach = em.getReference(creditosCollection1CreditosToAttach.getClass(), creditosCollection1CreditosToAttach.getIdCredito());
                attachedCreditosCollection1.add(creditosCollection1CreditosToAttach);
            }
            usuarios.setCreditosCollection1(attachedCreditosCollection1);
            Collection<Creditos> attachedCreditosCollection2 = new ArrayList<Creditos>();
            for (Creditos creditosCollection2CreditosToAttach : usuarios.getCreditosCollection2()) {
                creditosCollection2CreditosToAttach = em.getReference(creditosCollection2CreditosToAttach.getClass(), creditosCollection2CreditosToAttach.getIdCredito());
                attachedCreditosCollection2.add(creditosCollection2CreditosToAttach);
            }
            usuarios.setCreditosCollection2(attachedCreditosCollection2);
            em.persist(usuarios);
            for (Creditos creditosCollectionCreditos : usuarios.getCreditosCollection()) {
                Usuarios oldIdEmpleadoCodeudorOfCreditosCollectionCreditos = creditosCollectionCreditos.getIdEmpleadoCodeudor();
                creditosCollectionCreditos.setIdEmpleadoCodeudor(usuarios);
                creditosCollectionCreditos = em.merge(creditosCollectionCreditos);
                if (oldIdEmpleadoCodeudorOfCreditosCollectionCreditos != null) {
                    oldIdEmpleadoCodeudorOfCreditosCollectionCreditos.getCreditosCollection().remove(creditosCollectionCreditos);
                    oldIdEmpleadoCodeudorOfCreditosCollectionCreditos = em.merge(oldIdEmpleadoCodeudorOfCreditosCollectionCreditos);
                }
            }
            for (Creditos creditosCollection1Creditos : usuarios.getCreditosCollection1()) {
                Usuarios oldIdEmpleadoAdministradorOfCreditosCollection1Creditos = creditosCollection1Creditos.getIdEmpleadoAdministrador();
                creditosCollection1Creditos.setIdEmpleadoAdministrador(usuarios);
                creditosCollection1Creditos = em.merge(creditosCollection1Creditos);
                if (oldIdEmpleadoAdministradorOfCreditosCollection1Creditos != null) {
                    oldIdEmpleadoAdministradorOfCreditosCollection1Creditos.getCreditosCollection1().remove(creditosCollection1Creditos);
                    oldIdEmpleadoAdministradorOfCreditosCollection1Creditos = em.merge(oldIdEmpleadoAdministradorOfCreditosCollection1Creditos);
                }
            }
            for (Creditos creditosCollection2Creditos : usuarios.getCreditosCollection2()) {
                Usuarios oldIdEmpleadoTitularOfCreditosCollection2Creditos = creditosCollection2Creditos.getIdEmpleadoTitular();
                creditosCollection2Creditos.setIdEmpleadoTitular(usuarios);
                creditosCollection2Creditos = em.merge(creditosCollection2Creditos);
                if (oldIdEmpleadoTitularOfCreditosCollection2Creditos != null) {
                    oldIdEmpleadoTitularOfCreditosCollection2Creditos.getCreditosCollection2().remove(creditosCollection2Creditos);
                    oldIdEmpleadoTitularOfCreditosCollection2Creditos = em.merge(oldIdEmpleadoTitularOfCreditosCollection2Creditos);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findUsuarios(usuarios.getIdUsuario()) != null) {
                throw new PreexistingEntityException("Usuarios " + usuarios + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Usuarios usuarios) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Usuarios persistentUsuarios = em.find(Usuarios.class, usuarios.getIdUsuario());
            Collection<Creditos> creditosCollectionOld = persistentUsuarios.getCreditosCollection();
            Collection<Creditos> creditosCollectionNew = usuarios.getCreditosCollection();
            Collection<Creditos> creditosCollection1Old = persistentUsuarios.getCreditosCollection1();
            Collection<Creditos> creditosCollection1New = usuarios.getCreditosCollection1();
            Collection<Creditos> creditosCollection2Old = persistentUsuarios.getCreditosCollection2();
            Collection<Creditos> creditosCollection2New = usuarios.getCreditosCollection2();
            List<String> illegalOrphanMessages = null;
            for (Creditos creditosCollectionOldCreditos : creditosCollectionOld) {
                if (!creditosCollectionNew.contains(creditosCollectionOldCreditos)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Creditos " + creditosCollectionOldCreditos + " since its idEmpleadoCodeudor field is not nullable.");
                }
            }
            for (Creditos creditosCollection1OldCreditos : creditosCollection1Old) {
                if (!creditosCollection1New.contains(creditosCollection1OldCreditos)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Creditos " + creditosCollection1OldCreditos + " since its idEmpleadoAdministrador field is not nullable.");
                }
            }
            for (Creditos creditosCollection2OldCreditos : creditosCollection2Old) {
                if (!creditosCollection2New.contains(creditosCollection2OldCreditos)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Creditos " + creditosCollection2OldCreditos + " since its idEmpleadoTitular field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Creditos> attachedCreditosCollectionNew = new ArrayList<Creditos>();
            for (Creditos creditosCollectionNewCreditosToAttach : creditosCollectionNew) {
                creditosCollectionNewCreditosToAttach = em.getReference(creditosCollectionNewCreditosToAttach.getClass(), creditosCollectionNewCreditosToAttach.getIdCredito());
                attachedCreditosCollectionNew.add(creditosCollectionNewCreditosToAttach);
            }
            creditosCollectionNew = attachedCreditosCollectionNew;
            usuarios.setCreditosCollection(creditosCollectionNew);
            Collection<Creditos> attachedCreditosCollection1New = new ArrayList<Creditos>();
            for (Creditos creditosCollection1NewCreditosToAttach : creditosCollection1New) {
                creditosCollection1NewCreditosToAttach = em.getReference(creditosCollection1NewCreditosToAttach.getClass(), creditosCollection1NewCreditosToAttach.getIdCredito());
                attachedCreditosCollection1New.add(creditosCollection1NewCreditosToAttach);
            }
            creditosCollection1New = attachedCreditosCollection1New;
            usuarios.setCreditosCollection1(creditosCollection1New);
            Collection<Creditos> attachedCreditosCollection2New = new ArrayList<Creditos>();
            for (Creditos creditosCollection2NewCreditosToAttach : creditosCollection2New) {
                creditosCollection2NewCreditosToAttach = em.getReference(creditosCollection2NewCreditosToAttach.getClass(), creditosCollection2NewCreditosToAttach.getIdCredito());
                attachedCreditosCollection2New.add(creditosCollection2NewCreditosToAttach);
            }
            creditosCollection2New = attachedCreditosCollection2New;
            usuarios.setCreditosCollection2(creditosCollection2New);
            usuarios = em.merge(usuarios);
            for (Creditos creditosCollectionNewCreditos : creditosCollectionNew) {
                if (!creditosCollectionOld.contains(creditosCollectionNewCreditos)) {
                    Usuarios oldIdEmpleadoCodeudorOfCreditosCollectionNewCreditos = creditosCollectionNewCreditos.getIdEmpleadoCodeudor();
                    creditosCollectionNewCreditos.setIdEmpleadoCodeudor(usuarios);
                    creditosCollectionNewCreditos = em.merge(creditosCollectionNewCreditos);
                    if (oldIdEmpleadoCodeudorOfCreditosCollectionNewCreditos != null && !oldIdEmpleadoCodeudorOfCreditosCollectionNewCreditos.equals(usuarios)) {
                        oldIdEmpleadoCodeudorOfCreditosCollectionNewCreditos.getCreditosCollection().remove(creditosCollectionNewCreditos);
                        oldIdEmpleadoCodeudorOfCreditosCollectionNewCreditos = em.merge(oldIdEmpleadoCodeudorOfCreditosCollectionNewCreditos);
                    }
                }
            }
            for (Creditos creditosCollection1NewCreditos : creditosCollection1New) {
                if (!creditosCollection1Old.contains(creditosCollection1NewCreditos)) {
                    Usuarios oldIdEmpleadoAdministradorOfCreditosCollection1NewCreditos = creditosCollection1NewCreditos.getIdEmpleadoAdministrador();
                    creditosCollection1NewCreditos.setIdEmpleadoAdministrador(usuarios);
                    creditosCollection1NewCreditos = em.merge(creditosCollection1NewCreditos);
                    if (oldIdEmpleadoAdministradorOfCreditosCollection1NewCreditos != null && !oldIdEmpleadoAdministradorOfCreditosCollection1NewCreditos.equals(usuarios)) {
                        oldIdEmpleadoAdministradorOfCreditosCollection1NewCreditos.getCreditosCollection1().remove(creditosCollection1NewCreditos);
                        oldIdEmpleadoAdministradorOfCreditosCollection1NewCreditos = em.merge(oldIdEmpleadoAdministradorOfCreditosCollection1NewCreditos);
                    }
                }
            }
            for (Creditos creditosCollection2NewCreditos : creditosCollection2New) {
                if (!creditosCollection2Old.contains(creditosCollection2NewCreditos)) {
                    Usuarios oldIdEmpleadoTitularOfCreditosCollection2NewCreditos = creditosCollection2NewCreditos.getIdEmpleadoTitular();
                    creditosCollection2NewCreditos.setIdEmpleadoTitular(usuarios);
                    creditosCollection2NewCreditos = em.merge(creditosCollection2NewCreditos);
                    if (oldIdEmpleadoTitularOfCreditosCollection2NewCreditos != null && !oldIdEmpleadoTitularOfCreditosCollection2NewCreditos.equals(usuarios)) {
                        oldIdEmpleadoTitularOfCreditosCollection2NewCreditos.getCreditosCollection2().remove(creditosCollection2NewCreditos);
                        oldIdEmpleadoTitularOfCreditosCollection2NewCreditos = em.merge(oldIdEmpleadoTitularOfCreditosCollection2NewCreditos);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = usuarios.getIdUsuario();
                if (findUsuarios(id) == null) {
                    throw new NonexistentEntityException("The usuarios with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Usuarios usuarios;
            try {
                usuarios = em.getReference(Usuarios.class, id);
                usuarios.getIdUsuario();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The usuarios with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Creditos> creditosCollectionOrphanCheck = usuarios.getCreditosCollection();
            for (Creditos creditosCollectionOrphanCheckCreditos : creditosCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Usuarios (" + usuarios + ") cannot be destroyed since the Creditos " + creditosCollectionOrphanCheckCreditos + " in its creditosCollection field has a non-nullable idEmpleadoCodeudor field.");
            }
            Collection<Creditos> creditosCollection1OrphanCheck = usuarios.getCreditosCollection1();
            for (Creditos creditosCollection1OrphanCheckCreditos : creditosCollection1OrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Usuarios (" + usuarios + ") cannot be destroyed since the Creditos " + creditosCollection1OrphanCheckCreditos + " in its creditosCollection1 field has a non-nullable idEmpleadoAdministrador field.");
            }
            Collection<Creditos> creditosCollection2OrphanCheck = usuarios.getCreditosCollection2();
            for (Creditos creditosCollection2OrphanCheckCreditos : creditosCollection2OrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Usuarios (" + usuarios + ") cannot be destroyed since the Creditos " + creditosCollection2OrphanCheckCreditos + " in its creditosCollection2 field has a non-nullable idEmpleadoTitular field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(usuarios);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Usuarios> findUsuariosEntities() {
        return findUsuariosEntities(true, -1, -1);
    }

    public List<Usuarios> findUsuariosEntities(int maxResults, int firstResult) {
        return findUsuariosEntities(false, maxResults, firstResult);
    }

    private List<Usuarios> findUsuariosEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Usuarios.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Usuarios findUsuarios(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Usuarios.class, id);
        } finally {
            em.close();
        }
    }

    public int getUsuariosCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Usuarios> rt = cq.from(Usuarios.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
